package com.logos.musicframe.controller;

import com.logos.musicframe.chatmemory.ChatHistoryRepository;
import com.logos.musicframe.resp.MsgResp;
import com.logos.musicframe.result.Result;
import com.logos.musicframe.utils.UserInfoUtil;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.ai.chat.messages.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.List;

/**
 * @author logos
 * date 2025/6/17 15:24
 * @version v1.0
 * @Package com.logos.musicframe.controller
 */
@Component
public class ChatHistoryController {

    @Autowired
    private ChatHistoryRepository chatHistoryRepository;

    @Autowired
    private ChatMemory chatMemory;

    @Autowired
    private UserInfoUtil userInfoUtil;

    /**
     * 查看历史会话列表
     */
    @GetMapping
    public Result<List<String>> getChatIds() {
        String userId = String.valueOf(userInfoUtil.getUserId());
        List<String> chatIdList = chatHistoryRepository.getChatIdList(userId);
        return Result.ok(chatIdList);
    }

    /**
     * 查看历史会话
     * @param chatId 会话id
     */
    @GetMapping("/{chatId}")
    public Result<List<MsgResp>> getChatHistory(@PathVariable("chatId") String chatId) {
        List<Message> messages = chatMemory.get(chatId, Integer.MAX_VALUE);
        if (messages == null) {
            return null;
        }
        List<MsgResp> result = messages.stream().map(MsgResp::new).toList();
        return Result.ok(result);
    }
}
